<template>
<div class="product-list">
<!--搜索-->
  <searchBox @submit="searchSubmit" :data="categoryList"/>
  <a-button class="product-btn">
    <router-link :to="{name:'ProductAdd'}">添加商品</router-link>
  </a-button>
<!--表格-->
  <productTable
    :data="tableDate"
    :page="page"
    @change="changePage"
    @edit="editProduct"
    @remove="removeProduct"
  />
</div>
</template>

<script>
import searchBox from '@/components/search.vue';
import productTable from '@/components/productTable.vue';
import api from '@/api/product';
import categoryapi from '@/api/category';

export default {
  data() {
    return {
      // 表格数据
      tableDate: [],
      // 搜索数据
      searchFrom: {},
      // 类目数据
      categoryList: [],
      // 分页数据
      page: {
        current: 1,
        pageSize: 10,
        showSizeChanger: true,
        total: 1,
      },
      // 类目映射
      categoryObj: {},
    };
  },
  components: {
    searchBox,
    productTable,
  },
  async created() {
    await categoryapi.list().then((res) => {
      this.categoryList = res.data;
      res.data.forEach((item) => {
        this.categoryObj[item.id] = item;
      });
    });
    this.geTableDate();
  },
  methods: {
    // 点击搜索
    searchSubmit(form) {
      this.searchFrom = form;
      this.geTableDate();
    },
    // 获取表格数据
    geTableDate() {
      api.list({
        page: this.page.current,
        size: this.page.pageSize,
        ...this.searchFrom,
      }).then((res) => {
        this.page.total = res.total;
        this.tableDate = res.data.map((item) => ({
          ...item,
          categoryName: this.categoryObj[item.category].name,
        }));
      });
    },
    // 翻页
    changePage(page) {
      this.page = page;
      this.geTableDate();
    },
    // 编辑列表数据
    editProduct(record) {
      this.$router.push({
        name: 'ProductEdit',
        params: {
          id: record.id,
        },
      });
    },
    // 移除
    removeProduct(record) {
      this.$confirm({
        title: '确认删除',
        content: () => <div style="color:red;">{ `确认删除产品标题为${record.title}的产品吗？`}</div>,
        onOk: () => {
          api.remove({
            id: record.id,
          }).then(() => {
            // 删除后重新获取表格数据
            this.geTableDate();
          });
        },
        onCancel() {
          console.log('Cancel');
        },
        class: 'test',
      });
    },
  },
};
</script>

<style scoped lang="less">
.product-list{
  position: relative;
  .product-btn{
    position: absolute;
    right: 10px;
    top: 14px;
  }
}
</style>
